package epam.bookShelf.stuff;

import epam.bookShelf.bookStuff.Book;

import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Library {
	private ArrayList<Book> books;
	private String name;
	private String description;
	
	public Library() {
	    books = new ArrayList<Book>();
	}
	
	public void addBook(Book book) {
	    books.add(book);
	}
	
	public String getXML() {	
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;
        Document doc;
        
        try {
			docBuilder = dbfac.newDocumentBuilder();
	        doc = docBuilder.newDocument();
	        
            Element root = doc.createElement("books");
            doc.appendChild(root);
            
    		for (Book b : books) {
    			root.appendChild(b.getDOMElement(doc));
    		}
    		           
            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans;
			try {
				trans = transfac.newTransformer();
				trans.setOutputProperty(OutputKeys.INDENT, "yes");
				//trans.setOutputProperty(OutputKeys.STANDALONE, "no");

				//create string from xml tree
				StringWriter sw = new StringWriter();
				StreamResult result = new StreamResult(sw);
				DOMSource source = new DOMSource(doc);
				trans.transform(source, result);

				return sw.toString();
			} catch (TransformerConfigurationException e1) {
				e1.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	//******************** Getters/Setters area ********************
    public ArrayList<Book> getBooks() {
        return books;
    }
    public void setBooks(ArrayList<Book> books) {
        this.books = books;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

	
}